<template>
  <view class="container">
    <!-- <text class="title">我发布的帖子</text> -->

   
    <!-- 悬浮发布按钮 -->
    <view class="publish-btn" @tap="goToPublish">
      <text class="iconfont icon-edit">+</text>
    </view>

    <!-- 帖子列表 -->
    <scroll-view 
      class="post-list"
      scroll-y
      @scrolltolower="loadMore"
      v-if="posts.length > 0"
    >
      <view 
        v-for="(post, index) in posts" 
        :key="post.postId"
        class="post-item"
        @tap="goToDetail(post.postId)"
      >
        <view class="post-header">
          <image class="avatar" :src="getStaticFilePath(post.user.avatar)" mode="aspectFill"></image>
          <view class="post-info">
            <text class="username">{{ post.user.nickName }}</text>
            <text class="time">{{ post.createTime }}</text>
          </view>
        </view>
        <view class="post-content">
          <text class="title-text">{{ post.title }}</text>
          <text class="content-text">{{ post.content }}</text>
          <view class="image-list" v-if="post.images && post.images.length">
            <image 
              v-for="(img, imgIndex) in processedImages(post.images)" 
              :key="imgIndex"
              :src="getStaticFilePath(img)"
              mode="aspectFill"
              @tap.stop="previewImage(processedImages(post.images), imgIndex)"
            ></image>
          </view>
        </view>
        <view class="post-footer">
          <view class="action-item" @tap.stop="handleLike(post, index)">
            <uni-icons :type="post.isLiked ? 'heart-filled' : 'heart'" :color="post.isLiked ? '#FF5722' : '#666'" size="20"></uni-icons>
            <text>{{ post.likes }}</text>
          </view>
          <view class="action-item">
            <uni-icons type="chat" color="#666" size="20"></uni-icons>
            <text>{{ post.comments }}</text>
          </view>
          <view class="action-item edit-btn" @tap.stop="handleEditPost(post)">
            <uni-icons type="compose" color="#4B7BFF" size="20"></uni-icons>
            <text>编辑</text>
          </view>
          <view class="action-item delete-btn" @tap.stop="handleDeletePost(post.postId)">
            <uni-icons type="trash" color="#FF4D4F" size="20"></uni-icons>
            <text>删除</text>
          </view>
        </view>
      </view>
      <uni-load-more :status="loadingStatus" :content-text="loadMoreText"></uni-load-more>
    </scroll-view>

    <view class="no-data" v-else>
      <text>暂无发布的帖子</text>
    </view>
  </view>
</template>

<script>
import { listPost, delPost, listComment, likeTarget } from '../../api/community';
import UniIcons from '@/uni_modules/uni-icons/components/uni-icons/uni-icons.vue';
import UniLoadMore from '@/uni_modules/uni-load-more/components/uni-load-more/uni-load-more.vue';
import { getStaticFilePath } from '../../utils/common';

export default {
  components: {
    UniIcons,
    UniLoadMore
  },
  data() {
    return {
      posts: [],
      pageNum: 1,
      pageSize: 10,
      loading: false,
      hasMore: true,
      needRefresh: false
    };
  },
  computed: {
    loadingStatus() {
      if (this.loading) {
        return 'loading';
      } else if (this.hasMore) {
        return 'more';
      } else {
        return 'noMore';
      }
    },
    loadMoreText() {
      if (this.hasMore) {
        return { contentdown: '上拉显示更多', contentrefresh: '正在加载...', contentnomore: '没有更多数据了' };
      } else {
        return { contentdown: '没有更多数据了', contentrefresh: '正在加载...', contentnomore: '没有更多数据了' };
      }
    }
  },
  onLoad() {
    console.log('my-posts.vue: onLoad');
    this.loadPosts();
    // 添加事件监听
    uni.$on('refreshMyPosts', this.handleRefreshPosts);
  },
  onShow() {
    console.log('my-posts.vue: onShow');
    // 检查是否需要刷新
    if (this.needRefresh || uni.getStorageSync('shouldRefreshMyPosts')) {
      console.log('my-posts.vue: Refresh needed, refreshing posts...');
      this.handleRefreshPosts();
      this.needRefresh = false;
      uni.removeStorageSync('shouldRefreshMyPosts');
    }
  },
  onUnload() {
    console.log('my-posts.vue: onUnload, removing event listener');
    uni.$off('refreshMyPosts', this.handleRefreshPosts);
  },
  onHide() {
    console.log('my-posts.vue: onHide');
    // 页面隐藏时设置刷新标记
    this.needRefresh = true;
  },
  methods: {
    getStaticFilePath,
    // 处理图片字符串为数组
    processedImages(images) {
      if (typeof images === 'string' && images) {
        return images.split(',');
      } else if (Array.isArray(images)) {
        return images.filter(img => img.length > 0);
      }
      return [];
    },
    // 预览图片
    previewImage(images, current) {
      const urls = images.map(img => this.getStaticFilePath(img));
      uni.previewImage({
        urls: urls,
        current: urls[current]
      });
    },
    // 处理刷新事件
    async handleRefreshPosts() {
      console.log('my-posts.vue: handleRefreshPosts called');
      try {
        this.pageNum = 1;
        this.posts = [];
        this.hasMore = true;
        await this.loadPosts();
        console.log('my-posts.vue: Refresh completed successfully');
      } catch (error) {
        console.error('my-posts.vue: Refresh failed:', error);
        // 如果刷新失败，保持刷新标记
        this.needRefresh = true;
        uni.setStorageSync('shouldRefreshMyPosts', true);
      }
    },
    // 加载帖子列表
    async loadPosts() {
      if (this.loading || (!this.hasMore && this.pageNum > 1)) return;
      
      console.log('my-posts.vue: Loading posts, page:', this.pageNum);
      this.loading = true;
      
      try {
        const query = {
          pageNum: this.pageNum,
          pageSize: this.pageSize
        };
        
        const res = await listPost(query);
        console.log('my-posts.vue: Load posts response:', res);
        
        if (res.code === 200) {
          const newPosts = res.rows.map(post => {
            if (!post.user) {
              post.user = { nickName: '匿名用户', avatar: '' };
            }
            return post;
          });
          
          if (this.pageNum === 1) {
            this.posts = newPosts;
          } else {
            this.posts = [...this.posts, ...newPosts];
          }
          
          this.hasMore = res.rows.length === this.pageSize;
          if (this.hasMore) {
            this.pageNum++;
          }
          
          console.log('my-posts.vue: Posts loaded successfully, count:', newPosts.length);
        } else {
          console.error('my-posts.vue: Load posts failed:', res.msg);
          uni.showToast({
            title: res.msg || '加载我发布的帖子失败',
            icon: 'none'
          });
        }
      } catch (error) {
        console.error('my-posts.vue: Load posts error:', error);
        uni.showToast({
          title: '网络错误，加载失败',
          icon: 'none'
        });
      } finally {
        this.loading = false;
      }
    },
    // 跳转到帖子详情
    goToDetail(postId) {
      uni.navigateTo({
        url: `/pages/community/detail?postId=${postId}`
      });
    },
    // 跳转到发布帖子页面
    goToPublish() {
      uni.navigateTo({
        url: '/pages/community/publish'
      });
    },
    // 编辑帖子
    handleEditPost(post) {
      // 将帖子对象序列化后作为参数传递给发布页面
      const postJson = JSON.stringify(post);
      uni.navigateTo({
        url: `/pages/community/publish?postId=${post.postId}&postData=${encodeURIComponent(postJson)}&from=my-posts`
      });
    },
    // 删除帖子
    async handleDeletePost(postId) {
      uni.showModal({
        title: '提示',
        content: '确定要删除该帖子吗？',
        success: async (res) => {
          if (res.confirm) {
            try {
              const res = await delPost(postId);
              if (res.code === 200) {
                uni.showToast({
                  title: '删除成功',
                  icon: 'success'
                });
                // 刷新帖子列表
                this.pageNum = 1;
                this.posts = [];
                this.hasMore = true;
                this.loadPosts();
              } else {
                uni.showToast({
                  title: res.msg || '删除失败',
                  icon: 'none'
                });
              }
            } catch (error) {
              console.error('删除帖子异常:', error);
              uni.showToast({
                title: '网络错误，删除失败',
                icon: 'none'
              });
            }
          }
        }
      });
    },
    // 点赞/取消点赞
    async handleLike(post, index) {
      try {
        const res = await likeTarget('1', post.postId) // 1代表帖子
        if (res.code === 200) {
          if (res.data === 1) { // 点赞成功
            this.$set(this.posts[index], 'isLiked', true)
            this.$set(this.posts[index], 'likes', post.likes + 1)
            uni.showToast({
              title: '点赞成功',
              icon: 'success',
              duration: 500
            })
          } else { // 取消点赞
            this.$set(this.posts[index], 'isLiked', false)
            this.$set(this.posts[index], 'likes', post.likes - 1)
            uni.showToast({
              title: '取消点赞',
              icon: 'success',
              duration: 500
            })
          }
        } else {
          uni.showToast({
            title: res.msg || '操作失败',
            icon: 'none'
          })
          if (res.code === 401) {
            uni.showToast({
              title: '登录已过期，请重新登录',
              icon: 'none'
            });
            setTimeout(() => {
              uni.reLaunch({
                url: '/pages/login/login'
              });
            }, 1500);
          }
        }
      } catch (error) {
        console.error('点赞操作失败', error)
        if (error === '401') {
          uni.showToast({
            title: '登录已过期，请重新登录',
            icon: 'none'
          });
          setTimeout(() => {
            uni.reLaunch({
              url: '/pages/login/login'
            });
          }, 1500);
        } else {
          uni.showToast({
            title: '网络错误',
            icon: 'none'
          })
        }
      }
    },
    // 加载更多
    loadMore() {
      if (this.hasMore) {
        this.loadPosts();
      }
    }
  }
};
</script>

<style lang="scss">
.container {
  min-height: 100vh;
  background-color: #f5f5f5;
  padding: 20rpx 0;
}

.title {
  font-size: 36rpx;
  font-weight: bold;
  margin-bottom: 20rpx;
  display: block;
  text-align: center;
  color: #333;
}

.post-list {
  height: calc(100vh - 80rpx - 120rpx); /* 减去标题高度和发布按钮高度 */
  padding: 0 20rpx;
  box-sizing: border-box;
}

.post-item {
  background-color: #fff;
  border-radius: 16rpx;
  margin-bottom: 20rpx;
  padding: 30rpx;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);

  .post-header {
    display: flex;
    align-items: center;
    margin-bottom: 20rpx;

    .avatar {
      width: 80rpx;
      height: 80rpx;
      border-radius: 50%;
      margin-right: 20rpx;
    }

    .post-info {
      display: flex;
      flex-direction: column;

      .username {
        font-size: 32rpx;
        font-weight: bold;
        color: #333;
      }

      .time {
        font-size: 24rpx;
        color: #999;
      }
    }
  }

  .post-content {
    margin-bottom: 20rpx;

    .title-text {
      font-size: 36rpx;
      font-weight: bold;
      color: #333;
      margin-bottom: 10rpx;
      display: block;
    }

    .content-text {
      font-size: 28rpx;
      color: #555;
      line-height: 1.6;
      display: -webkit-box;
      -webkit-box-orient: vertical;
      -webkit-line-clamp: 3; /* 最多显示3行 */
      overflow: hidden;
      text-overflow: ellipsis;
    }

    .image-list {
      display: flex;
      flex-wrap: wrap;
      margin-top: 20rpx;

      image {
        width: 220rpx;
        height: 220rpx;
        margin-right: 10rpx;
        margin-bottom: 10rpx;
        border-radius: 8rpx;

        &:nth-child(3n) {
          margin-right: 0;
        }
      }
    }
  }

  .post-footer {
    display: flex;
    justify-content: flex-end; /* 右对齐 */
    margin-top: 20rpx;
    padding-top: 20rpx;
    border-top: 1rpx solid #eee;

    .action-item {
      display: flex;
      align-items: center;
      font-size: 24rpx;
      color: #999;
      margin-left: 30rpx; /* 增加间距 */
      
      .uni-icons {
        margin-right: 8rpx;
      }

      &.edit-btn {
        color: #4B7BFF;
      }

      &.delete-btn {
        color: #FF4D4F;
      }
    }
  }
}

.publish-btn {
  position: fixed;
  bottom: 200rpx;
  right: 40rpx;
  width: 100rpx;
  height: 100rpx;
  background-color: #1E90FF;
  border-radius: 50%;
  display: flex;
  justify-content: center;
  align-items: center;
  box-shadow: 0 8rpx 16rpx rgba(0, 119, 255, 0.3);
  z-index: 99;

  .icon-edit {
    font-size: 60rpx;
    color: #fff;
    font-weight: bold;
  }
}

.no-data {
  text-align: center;
  padding: 50rpx;
  color: #999;
  font-size: 28rpx;
}
</style> 